package com.aspire.shiro.servlet;

import com.aspire.shiro.service.LoginService;
import com.aspire.shiro.service.impl.LoginServiceImpl;
import com.aspire.shiro.service.impl.SecurityServiceImpl;
import org.apache.shiro.authc.UsernamePasswordToken;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 登陆的web层
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名和密码
        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        SecurityServiceImpl securityService = new SecurityServiceImpl();
        //Map<String, String> admin = securityService.getPasswordByUsername("admin");
        //构建登陆使用的token
        UsernamePasswordToken token=new UsernamePasswordToken(loginName,password);
        //登陆操作
        LoginService loginService=new LoginServiceImpl();
        boolean login = loginService.login(token);
        //登陆成功-->跳转首页
        if(login){
            req.getRequestDispatcher("/home").forward(req,resp);
            return;
        }
        //登陆失败-->继续登陆
        resp.sendRedirect("login.jsp");


    }
}
